import Vue from "vue";

// 首页计算因数
Vue.prototype.$getRate = function (
    scroll = 0,
    start = 0,
    distance = 0,
    height
) {
    if (height) (start = start * height), (distance = distance * height);
    return Math.min(1, Math.max(scroll - start, 0) / distance);
};
Vue.prototype.$clamp = function (min = 0, num = 0, max = 0) {
    return Math.min(Math.max(num, min), max);
};
// 时间格式化
Vue.prototype.$timeFormat = function (value, format) {
    if (!value) {
        return "";
    }

    let time = new Date(parseInt((value + "000").substr(0, 13)));
    let tpl = format || "YY-MM-DD hh:mm:ss";
    tpl = tpl.replace("YY", time.getFullYear());
    tpl = tpl.replace("MM", ("00" + (time.getMonth() + 1)).substr(-2, 2));
    tpl = tpl.replace("DD", ("00" + time.getDate()).substr(-2, 2));
    tpl = tpl.replace("hh", ("00" + time.getHours()).substr(-2, 2));
    tpl = tpl.replace("mm", ("00" + time.getMinutes()).substr(-2, 2));
    tpl = tpl.replace("ss", ("00" + time.getSeconds()).substr(-2, 2));
    return tpl;
};

//图片自动缩放，超出截断
Vue.prototype.$autoImage = function (width, height, scale) {
    var s = scale || 1; // 宽高比例，高/宽
    var w = parseInt(width) || 1;
    var h = parseInt(height) || 1;

    if (h / w > s) {
        return {
            width: "100%",
            height: (h / w / s) * 100 + "%",
            top: (1 - h / w / s) * 50 + "%",
        };
    } else {
        return {
            width: ((s * w) / h) * 100 + "%",
            height: "100%",
            left: (1 - (s * w) / h) * 50 + "%",
        };
    }
};

// 在容器内显示最大，最大边填满容器
Vue.prototype.$fiexImage = function (width, height, scale) {
    var s = scale || 1; // 宽高比例，高/宽
    var w = parseInt(width) || 1;
    var h = parseInt(height) || 1;
    if (h / w > s) {
        return {
            width: ((s * w) / h) * 100 + "%",
            height: "100%",
            left: (1 - (s * w) / h) * 50 + "%",
        };
    } else {
        return {
            width: "100%",
            height: (h / w / s) * 100 + "%",
            top: (1 - h / w / s) * 50 + "%",
        };
    }
};

// 模特从目标色获取底色
Vue.prototype.$modelBackgroundColor = function (color, model) {
    // 获取颜色10进制rgb值
    // 如果前面没有#，则补#
    const getColorRGB = (color) => {
        var sColor = ("#" + color.replace(/^#*/, "")).toLowerCase();
        //十六进制颜色值的正则表达式
        var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
        // 如果是16进制颜色
        if (sColor && reg.test(sColor)) {
            if (sColor.length === 4) {
                var sColorNew = "#";
                for (var i = 1; i < 4; i += 1) {
                    sColorNew += sColor
                        .slice(i, i + 1)
                        .concat(sColor.slice(i, i + 1));
                }
                sColor = sColorNew;
            }
            //处理六位的颜色值
            var sColorChange = [];
            for (var i = 1; i < 7; i += 2) {
                sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
            }
            return sColorChange;
        } else {
            return null;
        }
    };

    // 计算底色
    const calculateBlend = (opacity, out, mask) => {
        const color1 = out;
        const color2 = mask;
        const result = (color1 - color2 * opacity) / (1 - opacity);
        return Math.max(0, Math.min(255, Math.round(result)));
    };

    // 获取颜色
    const getColorHex = (val) => {
        const result = val.toString(16);
        if (!result) {
            return "00";
        } else if (result.length == 1) {
            return "0" + result;
        } else {
            return result.substr(0, 2);
        }
    };

    if (color && model && model.mask_color && model.mask_opacity) {
        // 目标颜色
        const outputRGB = getColorRGB(color);
        const maskRGB = getColorRGB(model.mask_color);
        const opacity = parseFloat(model.mask_opacity) || 0;

        if (outputRGB && maskRGB && opacity) {
            const R = calculateBlend(opacity, outputRGB[0], maskRGB[0]);
            const G = calculateBlend(opacity, outputRGB[1], maskRGB[1]);
            const B = calculateBlend(opacity, outputRGB[2], maskRGB[2]);

            return "#" + getColorHex(R) + getColorHex(G) + getColorHex(B);
        } else {
            return color;
        }
    } else {
        return color;
    }
};

// 获取纹理
Vue.prototype.$modelColorTaxture = (model, color) => {
    // 旧数据
    const surface = (model.surface_name || "").toLowerCase();
    const name = (surface.match(/^\S+/g) || [])[0] || "";

    // 新数据
    const model_color = JSON.parse(model.model_color || "{}");
    const taxture = model_color[color.color_id] || color["bg_" + name] || "";

    return taxture;
};

// 设计面名称修改
Vue.prototype.$getSurfaceNameFormat = (name) => {
    if (name && name.replace) {
        return name.replace(
            /\s+\w/gi,
            (str) => " " + str.substr(-1).toLowerCase()
        );
    } else {
        return name;
    }
};

// 获取商品类型（衣服、长裤、短裤）
Vue.prototype.$getClassifyBySpu = (spu) => {
    if (/^(11|21)\d/.test(spu)) {
        return "t-shirts"; // t 恤
    } else if (/^(12|22)\d/.test(spu)) {
        return "long-sleeve"; // 长袖
    } else if (/^(13|23)\d/.test(spu)) {
        return "hoodies"; // 帽衫
    } else if (/^(14|24)\d/.test(spu)) {
        return "sweat-shirts"; // 运动衫
    } else if (/^(15|25)\d/.test(spu)) {
        return "tank-tops"; // 背心
    } else if (/^(16|26)\d/.test(spu)) {
        return "shorts"; // 裤子
    } else if (/^(17|27)\d/.test(spu)) {
        return "pants"; // 短裤
    } else {
        return "clothes";
    }
};

// xml或url转json
Vue.prototype.$oceanCallbackFormat = (opt) => {
    const parseXml = (value) => {
        const result = {};
        const depth = [result]; // 深度

        value.match(/<?[^<>]*>?/gi).map((str) => {
            if (/^<\//.test(str)) {
                // 返回上一层
                depth.pop();
            } else if (/^<\w+/.test(str)) {
                // 进入一层
                const name = (str.match(/(?:<(\S+?)[\s>])/) || [])[1];
                const attr = {};
                const parent = depth[depth.length - 1];

                (str.match(/\S+="[^"]*"/g) || []).map((item) => {
                    const match = item.match(/(\S+)="([^"]*)"/) || [];
                    match[1] && (attr[match[1]] = match[2]);
                });

                if (!name || name == "response") {
                    // 没有名称，或是名称是response
                } else if (parent[name]) {
                    // 已经有内容了
                    const item = { attr: attr };
                    parent[name] = [parent[name]];
                    parent[name].push(item);
                    depth.push(parent[name]);
                } else {
                    parent[name] = { attr: attr };
                    depth.push(parent[name]);
                }
            } else if (str) {
                // 同层
                // 内容
                const parent = depth[depth.length - 1] || {};
                parent.text = str;
            }
        });

        const getObjectFormat = (parent) => {
            // 解析内容
            Object.keys(parent).map((key) => {
                const item = parent[key];
                if (!item) {
                    // 不管
                } else if (Array.isArray(item)) {
                    parent[key] = item.map((i) => getObjectFormat(i));
                } else if (!item.attr || JSON.stringify(item.attr) == "{}") {
                    // 节点为空
                    parent[key] = item.text || "";
                }
            });
            return parent;
        };

        return getObjectFormat(result);
    };

    const parseUrl = (value) => {
        const result = {};
        const list = value.match(/\w+=[^=&]*/g) || [];

        list.map((str) => {
            const match = str.match(/(\w+)=([^=&]*)/) || [];
            const name = decodeURIComponent(match[1]);
            const value = decodeURIComponent(match[2]).replace(/\+/g, " ");
            if (!name) {
                // 没有名称，则不管
            } else if (!result.hasOwnProperty(name)) {
                // 未赋值
                result[name] = value;
            } else if (Array.isArray(result[name])) {
                result[name].push(value);
            } else {
                result[name] = [result[name]];
                result[name].push(value);
            }
        });

        return result;
    };

    if (typeof opt != "string") {
        // 不是字符串
        return opt;
    } else if ((opt.match(/<\/?\w+[^>]*>/g) || []).length >= 2) {
        // xml
        return parseXml(opt);
    } else if ((opt.match(/\w+=[^=&]*/g) || []).length >= 1) {
        // url
        return parseUrl(opt);
    } else {
        // 其他
        return opt;
    }
};
// 获取图片缩略图
Vue.prototype.$getLitimgUrl = (url, type) => {
    if (url) {
        url = url.replace(/(-litimg)*?\.(png|jpe?g|gif)$/i, "-litimg.$2");
        if (type) {
            return Vue.prototype.$getImageUrl(url, type);
        } else {
            return Vue.prototype.$getImageUrl(url, "medium");
        }
    } else {
        return "";
    }
};

// 获取图片缩略图
Vue.prototype.$getImageWebPByUrl = (filepath) => {
    return filepath + "?x-oss-process=image/format,webp";
};

// 自动消失消息框
// 用法, this.$toast('提示文字','success')
Vue.prototype.$toast = (text, type) => {
    var toast = document.querySelector(".toast");

    // 如果toast还在，则不再执行
    if (toast) {
        clearTimeout(toast.timer_miss);
        clearTimeout(toast.timer_remove);

        toast.querySelector("p").innerHTML = text;
        toast.querySelector("p").setAttribute("class", type || "");
        toast.timer_miss = setTimeout(() => {
            toast.style.opacity = "0";
        }, 2500);
        toast.timer_remove = setTimeout(() => {
            document.body.removeChild(toast);
        }, 3000);
    } else {
        // 创建实例，挂载到文档以后的地方
        var toast = document.createElement("div");

        toast.setAttribute("class", "toast");
        toast.innerHTML = "<p>" + text + "</p>";
        toast.querySelector("p").setAttribute("class", type || "");
        toast.timer_miss = setTimeout(() => {
            toast.style.opacity = "0";
        }, 2500);
        toast.timer_remove = setTimeout(() => {
            document.body.removeChild(toast);
        }, 3000);
        document.body.appendChild(toast);
    }
};

// 确认弹窗
Vue.prototype.$confirm = (text, option) => {
    // 创建实例，挂载到文档以后的地方
    const confirm = document.createElement("div");
    const callbacks = [];
    const config = { primary: null, buttons: [], close: false };

    Object.keys(option || {}).map((key) => {
        const type = Object.prototype.toString.call(option[key]);
        if (key == "primary") {
            config.primary = option[key];
        } else if (key == "close") {
            config.close = !!option[key];
        } else if (type == "[object Function]") {
            callbacks.push({ name: key, callback: option[key] });
        }
    });

    config.buttons = callbacks.map((item) => {
        const primary = config.primary == item.name;
        const result = [];

        result.push(primary ? "<span primary>" : "<span>");
        result.push(item.name);
        result.push("</span>");

        return result.join("");
    });

    config.close = config.close ? '<i class="iconfont icon-guanbi"></i>' : "";

    confirm.innerHTML = "<cite><div></div><h6></h6>" + config.close + "</cite>";

    const body = confirm.querySelector("div");
    const buttons = confirm.querySelector("h6");
    const close = confirm.querySelector("i");

    confirm.setAttribute("class", "dialog-confirm");
    buttons.innerHTML = config.buttons.join("");
    body.innerHTML = text;

    // 关闭
    close &&
        (close.onclick = (e) => {
            document.body.removeChild(confirm);
        });

    // 按钮
    buttons.onclick = async (e) => {
        var target = e.target;
        const buttons = confirm.querySelectorAll("h6 span");
        const index = Array.prototype.slice.call(buttons).indexOf(target);
        const active = callbacks[index];

        if (active) {
            let intercept = await active.callback();
            if (intercept === undefined) {
                // 没有处理，关闭窗口
                document.body.removeChild(confirm);
            } else if (intercept) {
                // 拦截，但是允许关闭窗口
                document.body.removeChild(confirm);
            } else {
                // 拦截了，不关闭
            }
        }
    };

    document.body.appendChild(confirm);
    setTimeout((e) => confirm.classList.add("active"), 1);
};

// 本地localstore 用户配置
Vue.prototype.$localstoreConfig = (key, value) => {
    try {
        const config = JSON.parse(localStorage.getItem("CONFIG") || "{}");
        if (typeof value == "undefined") {
            // 获取值
            return config[key];
        } else {
            // 赋值
            config[key] = value;
            localStorage.setItem("CONFIG", JSON.stringify(config));
        }
    } catch (e) {
        // 错误
    }
};

// 用于测试环境调试
Vue.prototype.$debug = (...args) => {
    const env = process.env.NODE_ENV || "";

    if (env == "development") {
        for (var i in args) {
            const value = args[i];
            const type = Object.prototype.toString.call(value);

            if (type === "[object Function]") {
                value();
            } else if (
                type === "[object Object]" ||
                type === "[object Array]"
            ) {
                console.log(JSON.stringify(value));
            } else {
                console.log(value);
            }
        }
    }
};
